/**
 * Created by   :chengwei
 * Created time :2017/5/10
 * File explain :查看交易记录
 */
require.config({
  baseUrl: "../../libs",
  paths: {
    jquery: ["jquery/jquery-1.11.3"],
	vue: ["./vue2-4-1/vue"],
	header:["../components/my-header"],
    menu:["../components/my-menu"],
    layer: ["layer/layer"],
    zui: ["zui/js/zui"],
    bootTable: ["bootstrap-table-dist/dist/js/bootstrap-table"],
    bootTableCN: ["bootstrap-table-dist/dist/locale/bootstrap-table-zh-CN"],
    comConfig: ["../common/js/common-config"],
    QHPagination: ["../common/js/qhpager"],
    datetimepicker:["datetimepicker/js/datetimepicker.min"]
  }
});
require(["jquery"],function() {
  require(["bootTable","QHPagination"], function () {
    require(["vue","header","menu","zui", "layer", "bootTableCN", "comConfig","datetimepicker"], operationCodeFun)
  })
});
function operationCodeFun(vue,header,menu) {
  // 由于使用require框架整合，我们需要为layer.js配置读取css文件的路径
  layer.config({
    path: "../../libs/layer/"
  });
  window.initTop(vue);
  window.initMenu(vue);
  // 分页栏渲染参数
  var pagerOptions = {
    tag_Class: 'cmn-page_tag',//分页标签默认样式
    tag_on_Class: 'cmn-page_tag_on',//分页标签选中样式
    input_Class: 'cmn-pageInput',//分页搜索框样式
    showTags: 5,//标签省略距离
    pageSearch: true,//是否启用页面搜索跳转
    pageSizes:[]
  };

  // todo 声明变量
  var QHConfig = $("body").data("config");
  var _receiptHistory = window.qhPaginationFactroy("receiptHistory");//分页器的创建
  var userInfo = QHConfig.getSearchDataFun();//获取地址栏参数
  var manageDetail = JSON.parse(window.sessionStorage.getItem("detail"));//获得角色信息
  var userCode=manageDetail.userCode;
  var traderType={};
  var traderStatus={};
  // todo 页面初始化
  //日期选择器
  QHConfig.chooseDate();
  //可用余额
  getAccountDetail();
  getTrader();//获得交易类型
  //默认显示一个月
  oneMouth();
  //交易类型
  tradeTypeState("tradeType","trade",$(".bank-type"),"6");
  //接收地址上的参数类型表格自动改
  //todo 点击事件
  $("#id-trading-record").on("click",".close-trading,.bank-pay-btn",billClickFun);
  if(userInfo.type==2){
    $(".bank-type span").eq(3).addClass("active").siblings("span").removeClass("active");
  }
  //交易状态
  tradeTypeState("tradeStatus","states",$(".bank-status"),"");
  //交易记录表格
  tradingRecord();
  // todo 点击事件
  //点击面包屑
  $("#id-projectName").on("click",function() {
    parent.$("#id-main-frame").attr("src","tpl/mdu-sxb-account/mdu-sxb-account.html").click();
  });
  //时间start
  $(".beginTime").on("change",function () {
    removeActive();
    tradingTableRefresh();
    $(".endTime").datetimepicker("setStartDate",$(this).val());
  });
  $(".beginTime").on("click",function () {
    $(this).datetimepicker("update");
  });
  //时间end
  $(".endTime").on("change",function () {
    removeActive();
    tradingTableRefresh();
    $(".beginTime").datetimepicker("setEndDate",$(this).val());
  });
  $(".endTime").on("click",function () {
    $(this).datetimepicker("update");
  });

  //点击今天
  $(".today").on("click",function () {
    $(this).addClass("active");
    $(".bank-time-scope .mouth").removeClass("active");
    var today = new Date();
    var Y= today.getFullYear();
    var M=today.getMonth()+1;
    var D=today.getDate();
    M = M<10? "0"+M:M;
    D = D<10? "0"+D:D;
    var now = Y+"-"+M+"-"+D;
    $(".beginTime").val(now);
    $(".endTime").val(now);
    tradingTableRefresh();
  });
  //最近点击
  $(".bank-time-scope .mouth").on("click",showTime);
  // todo 其他功能函数
  //获取可用余额
  function getAccountDetail() {
    $.ajax(tokenAjax({
      url: QHConfig.url.getSXBInfo,
      contentType: "application/json",
      dataType: "json",
      success: function (data) {
        if (data.status == 200) {
          data = data.data;
          //转换金额格式
          data.availableBalance = data.availableBalance == null ? "" : outputmoney(data.availableBalance);
          $(".bank-balance-num").text(data.availableBalance);
        }
      }
    }))
  }
  //获取交易类型列表
  function tradeTypeState(urlName,dataName,ele,role) {
    $.ajax(tokenAjax({
      url: QHConfig.url[urlName]+role,
      contentType: "application/json",
      dataType: "json",
      async:false,
      success: function (data) {
        data = data.data;
        var str = '';
        for (var key in data) {
          str += `<span class="bank-month" data-${dataName}="${key}">${data[key]}</span>`
        }
        ele.append(str);
        ele.find(".bank-month").on("click", activeClick);
      }
    }))
  }
  //点击添加样式
  function activeClick() {
    $(this).addClass("active").siblings().removeClass("active");
    tradingTableRefresh()
  }
  //刷新表格
  function tradingTableRefresh() {
    $("#id-trading-record").bootstrapTable("refresh");
  }
  //充值成功回调
  if(userInfo.flag && userInfo.flag == 1) {
    $('[data-trade = "RECHARGE"]').click();
  }
  /*
   * 获取施小包交易记录
   * @author  chengwei
   * @Date    2017/5/10
   * */
  function tradingRecord() {
    $("#id-trading-record").bootstrapTable({
      url: QHConfig.url.getDealRecord,
      ajax:tableAjax,
      queryParams: function (params) {
        params.startTime = new Date($(".beginTime").val()).getTime()-28800000;
        params.endTime = $("today").hasClass("active")? new Date().getTime()+57599999:
        new Date($(".endTime").val()).getTime()+57599999;
        params.tradeType = $(".bank-type").find(".active").attr("data-trade");
        params.status = $(".bank-status").find(".active").attr("data-states");
        params.pageNum = params.offset / params.limit + 1;
        params.pageSize = params.limit;
        return params;
      },
      responseHandler: function (res) {
        _receiptHistory.setParameters(res.data.pageNum, res.data.pageSize, res.data.pages);
        _receiptHistory.render(res.data.pageNum);
        return QHConfig.BSTTableResHandler(res, resTradingRecordFmt);
      },
      onLoadSuccess: function () {
        $(".fixed-table-pagination").css("display", "none");
      },
      onClickRow: function(r, tr, i){
        if(i != 5){
          jumpDetails(r);
        }
      }
    });
    _receiptHistory.init($(".cmn-table-pager"), outHandler, pagerOptions);
  }
//点击行到账单详情
  function jumpDetails(row) {
    var txt = "";//当前账单类型
    $.each(traderType, function (k, v) {
      if (v == row.tradeType) {
        txt = k;
      }
    });
    layer.open({
      title: false,
      closeBtn:0,
      shade: 0.8,
      scrollbar:false,
      type: 2,
      area: ['100%', '100%'],
      content: `../../page/check-details/check-details.html?accountBill=${row.id}&type=2&amount=${row.amount}`
      +`&operName=${row.mainAccountRealName}&accountName=${row.oppositeAccountUserCode}`+
      `&tradeMemo=${row.tradeMemo}&bizzSn=${row.bizzSn}&transfer=${txt}&balance=${manageDetail.availableBalance}`+
      `&userCode=${manageDetail.userCode}&bizzSys=${row.bizzSys}&formBill=true`,
      end:function(){
        $("#id-trading-record").bootstrapTable("refresh");
      }
    })
  }

  //交易记录表格数据渲染和格式转换,$data:当前行对象
  function resTradingRecordFmt($data) {
    $data.createdAt = QHConfig.timeFmt($data.createdAt, 2);
    $data.amount = $data.fundFlow == "资金流入" ? "+" + outputmoney($data.amount) : "-" + outputmoney($data.amount);

  }

  /*
   * 分页器函数
   * @author  chengwei
   * @Date    2017/5/11
   * */
  function outHandler() {
    //执行bootstrapTable分页跳转
    $("#id-trading-record").bootstrapTable("selectPage", _receiptHistory.getPage());
  }
  //点击日期输入框样式消失
  function removeActive() {
    $(".bank-time-scope .mouth,.today").removeClass("active");
  }
  //默认一个月日期显示
  function oneMouth() {
    var dt = new Date();
    var Y=dt.getFullYear();
    var m=dt.getMonth()+1;
    var d=dt.getDate();
    m = m<10? "0"+m:m;
    d = d<10? "0"+d:d;
    dt = Y+"-"+m+"-"+d;
    $(".beginTime").val(getNewDate(1));
    $(".endTime").val(dt);
  }
  //最近的时间
  function showTime() {
    var mouthNum = $(this).attr("data-time");
    var dt = new Date();
    var Y=dt.getFullYear();
    var m=dt.getMonth()+1;
    var d=dt.getDate();
    m = m<10? "0"+m:m;
    d = d<10? "0"+d:d;
    dt = Y+"-"+m+"-"+d;
    $(".today").removeClass("active");
    $(this).addClass("active").siblings().removeClass("active");
    $(".beginTime").val(getNewDate(mouthNum));
    $(".endTime").val(dt);
    tradingTableRefresh();
  }
  //选择日期推前日期的方法
  function getNewDate(m){
    var m_days=[]; //各月份的总天数
    var dt=new Date();
    var myYear=dt.getFullYear();
    var month=dt.getMonth()+1;
    var d=dt.getDate();
    if(month>m)
      month=month-m;
    else{
      myYear--;
      month=month+12-m;
    }
    m_days=new Array(31,28+is_leap(myYear),31,30,31,30,31,31,30,31,30,31); //各月份的总天数
    if(d>m_days[month-1]){
      d=m_days[month-1];
    }
    month = month<10? "0"+month:month;
    d=d<10? "0"+d:d;
    return myYear+'-'+month+'-'+d;
  }
  function is_leap(year) {
    return (year%100==0?res=(year%400==0?1:0):res=(year%4==0?1:0));
  }
  //金额三位用逗号分开
  function outputmoney(number) {
    number = number + "".replace(/,/g, ""); //得到的数字里的逗号替换为空
    if (isNaN(number) || number == "") {
      return "";
    } //判断得到的数字是不是NaN和空的类型，返回为空
    number = Math.round(number * 100) / 100; //取小数点后数字进行四舍五入
    if (number < 0)
      return '-' + outputdollars(Math.floor(Math.abs(number) - 0) + '') + outputcents(Math.abs(number) - 0);
    else
      return outputdollars(Math.floor(number - 0) + '') + outputcents(number - 0);
  }

  //格式化金额
  function outputdollars(number) {
    if (number.length <= 3)
      return (number == '' ? '0' : number);
    else {
      var mod = number.length % 3;
      var output = (mod == 0 ? '' : (number.substring(0, mod)));
      for (var i = 0; i < Math.floor(number.length / 3); i++) {
        if ((mod == 0) && (i == 0))
          output += number.substring(mod + 3 * i, mod + 3 * i + 3);
        else
          output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
      }
      return (output);
    }
  }

  //判断小数点后的特殊情况，列入小于10
  function outputcents(amount) {
    amount = Math.round(((amount) - Math.floor(amount)) * 100);
    return (amount < 10 ? '.0' + amount : '.' + amount);
  }
  function billClickFun(){
    var billData=JSON.parse($(this).attr("data-bill"));
    var that=this;
    if($(this).hasClass("close-trading")){
      clickCloseFun(that)
    }else if($(this).hasClass("bank-pay-btn")){
      getBIzzSn(that);
    }
  }
  //交易关闭
  function clickCloseFun(that) {
    var billId = $(that).data("bill");//当前账单数据
    layer.confirm("您确定要关闭交易吗？关闭后，不能恢复", {
      btn: ["确定关闭", "取消"],
      title: "温馨提示"
    }, function () {
      $.ajax(tokenAjax({
        type: "PUT",
        url: QHConfig.url.billClose + "?accountBillId=" + billId.id,
        contentType: "application/json;charset=UTF-8",
        success: function (res) {
          if (res.message == "success") {
            tableRefresh();
          } else {
            layer.msg(res.message);
          }
        },
        error: function () {
          layer.alert("网络错误");
        }
      }));
      layer.closeAll();
    });
  }
  function getTrader() {
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeType+6,
      success: function (res) {
        traderType = res.data;//支付类型
      }
    }));
    $.ajax(tokenAjax({
      type: 'GET',
      async: false,
      url: QHConfig.url.tradeStatus,
      success: function (res) {
        traderStatus = res.data;//支付类型
      }
    }));
  }
  function getBIzzSn(that) {
    var billId = $(that).data("bill");//当前账单数据
    var txt = "";//当前账单类型
    var typeTradeSn=0;
    $.each(traderType, function (k, v) {
      if (v == billId.tradeType) {
        txt = k;
      }
    });

    $.ajax(tokenAjax({
      type:"POST",
      url:QHConfig.url.accountBillId+billId.id,
      contentType: "application/json;charset=UTF-8",
      dataType:"json",
      success:function(res){
        var payUrl = "";
        var msg = res.data;
        if(res.status==400){
          layer.msg(res.message)
        }else{
          if(billId.tradeType == "充值"){
            payUrl = "tpl/project-recharge/project-recharge.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance+ "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&userCode=" + userCode;
          }else{
            payUrl = "tpl/buyer-pay/buyer-pay.html" + "?transfer=" + txt + "&balance=" + manageDetail.availableBalance
              + "&amount=" + billId.amount + "&bizzSn=" + msg.bizzSn + "&operName=" + billId.mainAccountRealName + "&accountName=" + billId.oppositeAccountUserCode + "&userCode=" + manageDetail.userCode + "&bizzSys=" + msg.bizzSys+"&tradeMemo="+billId.tradeMemo+"&formBill=true";
          }
          layerNew2(payUrl);
        }
      }
    }));
  }
  function tableRefresh() {
    $("#id-trading-record").bootstrapTable("refresh");
  }
  //跳转到支付页面
  function layerNew2(url) {
    parent.layer.open({
      title: false,
      shade: 0.8,
      move: false,
      closeBtn: 0,
      resize: false,
      scrollbar: false,
      type: 2,
      area: ['100%', '100%'],
      content: url,
      end:function() {
        window.location.reload();
      }
    })
  }
}
function tradeTypeFmt(val, row, index) {
  if(row.oppositeAccountRealName==null){
    row.oppositeAccountRealName="";
  }
  return `<span class="transaction-type">${row.tradeType}</span><div class="transaction-card">${row.oppositeAccountRealName}</div>`
}
//操作类型模板
function handleFmt(val, row, index) {
  if ((row.status == "等待付款"&&row.fundFlow=="资金流出")||(row.status == "等待付款"&&row.tradeType=="充值")) {
    return `<span class="close-trading"  data-bill='${JSON.stringify(row)}'>关闭交易</span><input class="bank-pay-btn" type="button"  data-bill='${JSON.stringify(row)}' value="付款"/>`
  } else {
    return ``
  }
}
